import * as faceapi from "face-api.js";

let withBoxes = true
let predictedAges = []

main()

async function main(){
    // load model
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.ageGenderNet.loadFromUri('http://127.0.0.1:8888/weights')

    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video:{} })
        const videoEl = document.getElementById('inputVideo')
        videoEl.srcObject = stream
    } catch (error) {
        const errDom = document.createElement('div')
        errDom.className = 'err-container'
        errDom.innerText = '找不到请求的设备'
        document.querySelector('.page-container').prepend(errDom)
        alert(error.message)
    }

    closeLoading()    
}

window.onPlay = async()=>{
    const videoEl = document.getElementById('inputVideo')
    if(videoEl.paused || videoEl.ended){
        return setTimeout(()=>onPlay())
    }

    const result = await faceapi.detectSingleFace(videoEl).withAgeAndGender()
    if(result){
        const canvas = document.getElementById('overlay')
        const dims = faceapi.matchDimensions(canvas, videoEl, true)

        const resizedResult = faceapi.resizeResults(result, dims)
        if(withBoxes){
            faceapi.draw.drawDetections(canvas, resizedResult)
        }
        const { age, gender, genderProbability } = resizedResult
        const interpolatedAge = interpolateAgePredictions(age)
        new faceapi.draw.DrawTextField(
            [
                `${faceapi.utils.round(interpolatedAge, 0)} years`,
                `${gender} (${faceapi.utils.round(genderProbability)})`
            ],
            result.detection.box.bottomLeft
        ).draw(canvas)
    }
    
    setTimeout(()=>onPlay())
}

function interpolateAgePredictions(age){
    predictedAges = [age].concat(predictedAges).slice(0, 30)
    const avgPredictedAge = predictedAges.reduce((total,a)=>total+a) / predictedAges.length
    return avgPredictedAge
}